import * as Languages from "@/language";
// @ts-ignore
import { get } from "lodash";

declare type MaybeRef<T> = T | Ref<T>;

export type TranslatorOption = Record<string, string | number>;
export type Translator = (path: string, option?: TranslatorOption) => string;
export type LocaleContext = {
	locale: Ref<any>;
	lang: Ref<string>;
	t: Translator;
};

export const buildTranslator =
	(locale: MaybeRef<any>): Translator =>
	(path, option) =>
		translate(path, option, unref(locale));

export const translate = (path: string, option: undefined | TranslatorOption, locale: any): string =>
	(get(locale, path, path) as string).replace(/\{(\w+)\}/g, (_, key) => `${option?.[key] ?? `{${key}}`}`);

export const buildLocaleContext = (locale: MaybeRef<any>): LocaleContext => {
	const lang = computed(() => unref(locale).name);
	const localeRef = isRef(locale) ? locale : ref(locale);
	return {
		lang,
		locale: localeRef,
		t: buildTranslator(locale)
	};
};

export const useLocale = () => {
	const system = useStoreSystem();

	// @ts-ignore
	return buildLocaleContext(computed(() => Languages[system.language] || Languages["en"]));
};
